#include "stm32f10x.h"
#include "cat9555.h"
#include "i2c.h"
#include "global.h"



#define CAT9555_Waddr 0x40

//  ??CAT9555(I2C??)
#define  CAT9555_SLA         (0x40>>1)   //??CAT9555?????
#define  CAT9555_INPUT0       0//CAT9555???????0
#define  CAT9555_INPUT1       1//CAT9555???????1
#define  CAT9555_OUTPUT0      2//CAT9555???????0
#define  CAT9555_OUTPUT1      3//CAT9555???????1
#define  CAT9555_PI0          4//CAT9555?????0
#define  CAT9555_PI1          5//CAT9555?????1
#define  CAT9555_CFG0         6//CAT9555?????0
#define  CAT9555_CFG1         7//CAT9555?????1      




void CAT9555_Init(void)
{
    Single_Write(CAT9555_Waddr, CAT9555_CFG0, 0x00);
    Single_Write(CAT9555_Waddr, CAT9555_CFG1, 0x00);

    Single_Write(CAT9555_Waddr, CAT9555_PI0, 0x00);
    Single_Write(CAT9555_Waddr, CAT9555_PI1, 0x00);

    Single_Write(CAT9555_Waddr, CAT9555_OUTPUT0, 0x00);
    Single_Write(CAT9555_Waddr, CAT9555_OUTPUT1, 0x00);

}

void CAT9555_SetBit(uint8_t port, uint8_t bit)
{
    if (port == 1 || port == 0)
    {
        uint8_t value = Single_Read(CAT9555_Waddr, CAT9555_OUTPUT0 + port);
        SetBit(value, bit);
        Single_Write(CAT9555_Waddr, CAT9555_OUTPUT0 + port, value);
    }
}

void CAT9555_ResetBit(uint8_t port, uint8_t bit)
{
    if (port == 1 || port == 0)
    {
        uint8_t value = Single_Read(CAT9555_Waddr, CAT9555_OUTPUT0 + port);
        ClrBit(value, bit);
        Single_Write(CAT9555_Waddr, CAT9555_OUTPUT0 + port, value);
    }
}

void CAT9555_WriteBit(uint8_t port, uint8_t bit, uint8_t bitval)
{
    if (bitval == 1)
    {
        CAT9555_SetBit(port, bit);
    }
    else if (bitval == 0)
    {
        CAT9555_ResetBit(port, bit);
    }

}
uint8_t mStepMap[6][3] =
{
    {0, 0, 0},
    {0, 0, 1},
    {0, 1, 0},
    {0, 1, 1},
    {1, 0, 0},
    {1, 0, 1},
};



void SmSetSeteps(uint8_t axis, SM_MicroStep mstep)
{
    switch (axis)
    {
    case 0:
        CAT9555_WriteBit(0, 7, mStepMap[mstep][0]);
        CAT9555_WriteBit(0, 6, mStepMap[mstep][1]);
        CAT9555_WriteBit(0, 5, mStepMap[mstep][2]);
        break;
    case 1:
        CAT9555_WriteBit(0, 4, mStepMap[mstep][0]);
        CAT9555_WriteBit(0, 3, mStepMap[mstep][1]);
        CAT9555_WriteBit(0, 2, mStepMap[mstep][2]);
        break;
    case 2:
        CAT9555_WriteBit(0, 1, mStepMap[mstep][0]);
        CAT9555_WriteBit(0, 0, mStepMap[mstep][1]);
        CAT9555_WriteBit(1, 1, mStepMap[mstep][2]);
        break;
    case 3:
        CAT9555_WriteBit(1, 2, mStepMap[mstep][0]);
        CAT9555_WriteBit(1, 3, mStepMap[mstep][1]);
        CAT9555_WriteBit(1, 4, mStepMap[mstep][2]);
        break;
    case 4:
        CAT9555_WriteBit(1, 5, mStepMap[mstep][0]);
        CAT9555_WriteBit(1, 6, mStepMap[mstep][1]);
        CAT9555_WriteBit(1, 7, mStepMap[mstep][2]);
        break;
    }

}


